import 'package:flutter/material.dart';
import 'package:todo_app/model/toast.dart';
import 'package:todo_app/model/todo.dart';
import 'package:todo_app/util/dbhelper.dart';
import 'package:intl/intl.dart';

DbHelper helper = DbHelper();
final List<String> choices = const <String>[
  '删除记录',
];

const mnuSave = 'Save Todo & Back';
const mnuDelete = '删除记录';
const mnuBack = 'Back to List';

class TodoDetail extends StatefulWidget {
  final Todo todo;
  TodoDetail(this.todo);

  @override
  State<StatefulWidget> createState() => TodoDetailState(todo);
}

class TodoDetailState extends State {
  Todo todo;
  TodoDetailState(this.todo);
  final _priorities = ["高", "中", "低"];
  String _priority = "低";
  TextEditingController titleController = TextEditingController();
  TextEditingController descriptionController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    titleController.text = todo.title;
    descriptionController.text = todo.description;
    TextStyle textStyle = Theme.of(context).textTheme.title;
    return Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: false,
          title: Text(todo.title),
          leading: this.appBarLeading(),
          actions: <Widget>[
            PopupMenuButton<String>(
              onSelected: select,
              itemBuilder: (BuildContext context) {
                return choices.map((String choice) {
                  return PopupMenuItem<String>(
                    value: choice,
                    child: Text(choice),
                  );
                }).toList();
              },
            ),
          ],
        ),
        body: Padding(
            padding: EdgeInsets.only(top: 35.0, left: 10.0, right: 10.0),
            child: ListView(
              children: <Widget>[
                Column(
                  children: <Widget>[
                    TextField(
                      controller: titleController,
                      style: textStyle,
                      onChanged: (value) => this.updateTitle(),
                      decoration: InputDecoration(
                          labelText: "请输入名称",
                          labelStyle:
                              TextStyle(color: Colors.grey, fontSize: 18),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(5.0),
                          )),
                    ),
                    Padding(
                        padding: EdgeInsets.only(top: 15.0, bottom: 15.0),
                        child: TextField(
                          controller: descriptionController,
                          style: textStyle,
                          onChanged: (value) => this.updateDescription(),
                          decoration: InputDecoration(
                              labelText: "请输入相关描述",
                              labelStyle:
                                  TextStyle(color: Colors.grey, fontSize: 18),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(5.0),
                              )),
                        )),
                    ListTile(
                        title: DropdownButton<String>(
                      items: _priorities.map((String value) {
                        return DropdownMenuItem<String>(
                          value: value,
                          child: Text(value),
                        );
                      }).toList(),
                      style: textStyle,
                      value: retrievePriority(todo.priority),
                      onChanged: (value) => updatePriority(value),
                    )),
                    Padding(
                      padding: EdgeInsets.only(top: 75.0),
                      child: new RaisedButton(
                          child: Padding(
                              padding: EdgeInsets.only(
                                  top: 10.0, left: 40, right: 40, bottom: 10),
                              child: new Text(
                                todo.title != '' ? '编辑' : '发布',
                                style: new TextStyle(
                                  fontSize: 18.0, //textsize
                                  color: Colors.white, // textcolor
                                ),
                              )),
                          color: Theme.of(context).accentColor,
                          elevation: 4.0, //shadow
                          splashColor: Colors.blueGrey,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.all(Radius.circular(12)),
                          ),
                          onPressed: () {
                            if (todo.title == '') {
                              print(todo.title);
                              return Toast.toast(context, msg: "标题不能为空~");
                            }
                            if (todo.description == null) {
                              return Toast.toast(context, msg: "描述不能为空~");
                            }
                            save();
                          }),
                    )
                  ],
                )
              ],
            )));
  }

  void select(String value) async {
    int result;
    switch (value) {
      case mnuSave:
        break;
      case mnuDelete:
        if (todo.id == null) {
          return;
        }
        result = await helper.deleteTodo(todo.id);
        if (result != 0) {
          Navigator.pop(context, true);
          return Toast.toast(context, msg: "删除成功");
        }
        break;
      case mnuBack:
        break;
      default:
    }
  }

  void save() {
    todo.date = new DateFormat.yMd().format(DateTime.now());
    if (todo.id != null) {
      helper.updateTodo(todo);
    } else {
      helper.insertTodo(todo);
    }
    Toast.toast(context, msg: todo.edit == 1 ? "发布成功" : "编辑成功");
    Navigator.pop(context, true);
  }

  void updatePriority(String value) {
    switch (value) {
      case "高":
        todo.priority = 1;
        break;
      case "中":
        todo.priority = 2;
        break;
      case "低":
        todo.priority = 3;
        break;
    }
    setState(() {
      _priority = value;
    });
  }

  String retrievePriority(int value) {
    return _priorities[value - 1];
  }

  void updateTitle() {
    todo.title = titleController.text;
  }

  void updateDescription() {
    todo.description = descriptionController.text;
  }

  // 经过实验发现，leading是限制了大小的
  appBarLeading() {
    return new RaisedButton(
      onPressed: this.backUp,
      child: Icon(Icons.backspace),
      textColor: Colors.white,
      color: Colors.deepOrange,
      elevation: 0.0,
      disabledElevation: 0.0,
      highlightElevation: 0.0,
      // highlightColor: Colors.cyan,
      colorBrightness: Brightness.light,
      splashColor: Colors.deepOrange,
      padding: const EdgeInsets.all(5.0),
    );
  }

  backUp() {
    Navigator.pop(context, true);
  }
}
